<html>
<head>

<title>Groovy Goodness: Variable Scope in Scripts</title>

<script language="javascript" src="scripts/shCore.js"></script> 
<script language="javascript" src="scripts/shLegacy.js"></script> 
<script language="javascript" src="scripts/shBrushJava.js"></script> 
<script language="javascript" src="scripts/shBrushXml.js"></script> 
<script language="javascript" src="scripts/shBrushJScript.js"></script> 
<script language="javascript" src="scripts/shBrushGroovy.js"></script> 
<script language="javascript" src="scripts/shBrushPlain.js"></script> 
<script language="javascript" src="scripts/shBrushBash.js"></script> 
 
<link href="styles/reset.css" rel="stylesheet" type="text/css" />
<link href="styles/shCore.css" rel="stylesheet" type="text/css" />
<link type="text/css" rel="stylesheet" href="styles/shThemeRDark.css"/>
<link href="styles/blog.css" rel="stylesheet" type="text/css" />

</head>
<body>

<a href="index.html">Back to index</a>

<h3 class="post-title">Groovy Goodness: Variable Scope in Scripts</h3>

<div class="post">
<p>In Groovy scripts we can define variables with a type or with the <code>def</code> keyword. Or we can leave out any type definition or <code>def</code> keyword. This effects the scope of the variable. If we want to use the variable in a method we must not define it with a type or <code>def</code>. This way the variable is added to the script binding and can be accessed in a method.</p>
<pre class="brush:groovy">
String s = 'I am in local scope.'
def i = 42
counter = 0

def runIt() {
    try {
        assert 'I am in local scope.' == s
    } catch (e) {
        assert e instanceof MissingPropertyException
    }
    try {
        assert 42 == i
    } catch (e) {
        assert e instanceof MissingPropertyException
    }
    assert 0 == counter++
}

runIt()

assert 'I am in local scope.' == s
assert 42 == i
assert 1 == counter
</pre
</div>

<script language="javascript"> 
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.clipboardSwf = 'scripts/clipboard.swf';
SyntaxHighlighter.defaults['first-line'] = 0;
SyntaxHighlighter.defaults['auto-links'] = false;
SyntaxHighlighter.all();
dp.SyntaxHighlighter.HighlightAll('code');
</script>

</body>
</html>